# -*- coding: utf-8 -*-

import os
import sqlite3


class category(object):
    def __init__(self):
        self.nId = 0
        self.name = ''  # Rice smoke...
        self.isDefault = False


class dailyItem(object):
    def __init__(self):
        self.nId = 0
        self.category = 1
        self.nType = 0  # 0:incoming  1:outcoming
        self.money = 0.0
        self.datetime = ''    # 2015.07.20 22:21:13

class daily(object):
    def __init__(self):
        self.date = ''  # 2015.7.22
        self.memo = ''  # Description
        self.amount = ''    # Total money
        self.items = None # [dailyItem, dailyItem, ...]

class dbData(object):
    def __init__(self, dbPath):
        self.dbPath = os.path.join(dbPath, u'ab.db')
        self.init()
        
    def init(self):
        self.conn = sqlite3.connect(self.dbPath, check_same_thread=False)
        self.cursor = self.conn.cursor()

        sqlTable = """
        CREATE TABLE IF NOT EXISTS daily (t_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        t_categoryId INTEGER,
        t_type INTEGER,
        t_money REAL,
        t_datetime TEXT,
        t_isValid INTEGER DEFAULT 1);

        CREATE TABLE IF NOT EXISTS category (t_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        t_name TEXT,
        t_path TEXT);

        CREATE TABLE IF NOT EXISTS memo (t_date TEXT,
        t_memo TEXT,
        t_isValid INTEGER DEFAULT 1)
        """

        self.cursor.executescript(sqlTable)
        
        sqlInit = """
        select * from category
        """
        self.cursor.execute(sqlInit)
        if not self.cursor.fetchall():
            sqlAdd = """
            insert into category (t_name, t_path) values ('Rice', '');
            insert into category (t_name, t_path) values ('Smoke', '');
            insert into category (t_name, t_path) values ('Milk', '');
            insert into category (t_name, t_path) values ('Eat', '');
            insert into category (t_name, t_path) values ('Wan', '');
            insert into category (t_name, t_path) values ('G', '');
            """
            self.cursor.executescript(sqlAdd)

        self.conn.commit()

    def close(self):
        self.conn.close()

    def addDaily(self, daily):
        self.init()
        sql = """
        insert into daily(t_categoryId, t_type, t_money, t_datetime) values(?, ?, ?, ?)
        """
        self.cursor.execute(sql, (daily.category, daily.nType, daily.money, daily.datetime))
        self.conn.commit()

        self.close()

    def addMemo(self, memo):
        self.init()
        sql = """
        insert into memo(t_date, t_memo) values(?, ?)
        """
        self.cursor.execute(sql, (memo.date, memo.memo))

        self.close()

    def deleteItem(self):
        pass

    def searchDaily(self, date):
        self.init()

        self.close()

